package org.business.accounting.components;

import org.apache.tapestry5.ValidationException;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.corelib.components.BeanEditForm;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.business.accounting.beans.UserBean;
import org.business.accounting.interfaces.RegistrationHelper;
import org.business.accounting.interfaces.User;
import org.business.accounting.pages.Index;

@SuppressWarnings("unused")
public class Registration {
	
	private boolean isNotValid;
	private boolean isSecondTime;
	
	@Parameter(required = true)
	@Property
	private RegistrationHelper registrationHelper;
	
	@Inject 
	private Messages messages;
	
	@Parameter(required = true)
	@Property
	private String validatePassword;
	
	@Parameter
	@Property
	private String exclude;
	
	@Component
	private BeanEditForm regID;
	
	//
	// Event handlers
	//
	
	void onPrepare() {
		registrationHelper.setTmpUser(new UserBean());
	}
	
	void onValidate() throws ValidationException {		
		User user = registrationHelper.getTmpUser();

		if (isSecondTime) {
			if (user.getUserName() == null) {
				regID.recordError(messages.get("firstName-required-message"));
				isNotValid = true;
			}
			
			if (user.getFirstName() == null) {
				regID.recordError(messages.get("firstName-required-message"));
				isNotValid = true;
			} else if (user.getFirstName().length() > 15) {
					regID.recordError(messages.get("firstName-required-message"));
					isNotValid = true;
			}
			
			if (user.getLastName() == null) {
				regID.recordError(messages.get("secondName-required-message"));
				isNotValid = true;
			} else if (user.getLastName().length() > 15) {
				regID.recordError(messages.get("secondName-maxlength-message"));
				isNotValid = true;
			}
		
			
			if (!isNotValid) {
				if (!registrationHelper.register()) {
					regID.recordError(messages.get("username-allready-exists"));
					isNotValid = true;
				}
			}
			
		}
		if(isNotValid) {
			throw new ValidationException("registration-failed");
		}
		isSecondTime = true;
	}
	
	Object onAction() {
		if (isNotValid) {
			return null;
		}
		return Index.class;
	}
}
